package cmd

import (
	"encoding/json"
	"fmt"
	"github.com/spf13/cobra"
	"gobindc_test/client/utils"
	"gobindc_test/server/model"
	"net"
)

var getNameCmd = &cobra.Command{
	Use:   "get",
	Short: "get data",
	Long:  `Add a piece of data to your Tui service in string format`,
	Run: func(cmd *cobra.Command, args []string) {
		conn, err := net.Dial(deal, host+":"+port)
		if err != nil {
			fmt.Println(err.Error())
			return
		}
		defer conn.Close()
		requestData := model.SocketDataRequest{
			Password: utils.GetSha256(password),
			Cmd:      "get",
		}
		dataJson, err := json.Marshal(requestData)
		_, err = conn.Write(dataJson)
		if err != nil {
			fmt.Println(err.Error())
			return
		}
		var buf = make([]byte, 4096)
		n, err := conn.Read(buf)
		if err != nil {
			fmt.Println(err.Error())
			return
		}
		var repData model.SocketDataResponse
		err = json.Unmarshal(buf[:n], &repData)
		if err != nil {
			fmt.Println(err.Error())
			return
		}
		fmt.Println(repData.Data)
	},
}

func initGet() {
	getNameCmd.Flags().StringVarP(&password, "password", "p", "123456", "as your password to Tui")
	getNameCmd.Flags().StringVarP(&port, "port", "P", "317", "as your port to Tui")
	getNameCmd.Flags().StringVarP(&host, "host", "H", "127.0.0.1", "as your host to Tui")
	getNameCmd.Flags().StringVarP(&deal, "deal", "d", "tcp", "as your deal to Tui, tcp or udp")
	rootCmd.AddCommand(getNameCmd)
}
